package com.jule.teenpatti.mail.service;

import com.jule.core.jedis.StoredObjManager;
import com.jule.core.service.CronTaskManager;
import com.jule.core.service.ThreadPoolManager;
import com.jule.teenpatti.base.enums.RedisConst;
import com.jule.teenpatti.base.model.GameSvrRelationModel;
import com.jule.teenpatti.mail.config.Config;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Consumer;
import java.util.zip.CRC32;

/**
 * @author lyb 2018-06-19
 * 向Redis注册邮件服务器信息
 */
@Slf4j
public class RegisterService {
    public static int MAIL_SERVER_ID;
    public static String ADDRESS;

    private static class SingletonHolder {
        protected static final RegisterService instance = new RegisterService();
    }

    public static final RegisterService getInstance() {
        return SingletonHolder.instance;
    }

    public RegisterService() {
        ADDRESS = Config.BIND_IP + ":" + Config.BIND_PORT;
        MAIL_SERVER_ID = makeGameSvrId(ADDRESS);
    }

    /**
     * 向redis 注册服务器
     */
    public void onServiceStartUp() {
        try {
            GameSvrRelationModel relationModel = new GameSvrRelationModel(ADDRESS, "" + MAIL_SERVER_ID);

            if (StoredObjManager.sadd(RedisConst.MAIL_SVR_LIST.getProfix(), relationModel)) {
                StoredObjManager.hset(RedisConst.MAIL_SVR_EXPIRE.getProfix()+ relationModel.getGameSvrId(),
                        RedisConst.MAIL_SVR_EXPIRE.getField() + ADDRESS + MAIL_SERVER_ID,
                        System.currentTimeMillis() + "");
            }


            //每5秒修改一下最后修改时间
            Consumer<Object> callReqIsHasAck = obj -> {
                ThreadPoolManager.getInstance().addTask(new Runnable() {
                    @Override
                    public void run() {
                        StoredObjManager.hset(RedisConst.MAIL_SVR_EXPIRE.getProfix()+MAIL_SERVER_ID,
                                RedisConst.MAIL_SVR_EXPIRE.getField() + ADDRESS + MAIL_SERVER_ID,
                                System.currentTimeMillis() + "");
                    }
                });
            };
            CronTaskManager.CountDownTask taskConfig = new CronTaskManager.CountDownTask(0, callReqIsHasAck);
            CronTaskManager.getInstance().addCountDownJob(taskConfig.getName(), "CheckReqIsHasAck", taskConfig, "0/5 * * * * ?");


        } catch (Exception e) {
            log.debug(e.toString(),e);
        }
    }

    /**
     * 生成一个为一个服务器id
     *
     * @return
     */
    private int makeGameSvrId(String address) {
        CRC32 crc32 = new CRC32();
        crc32.update(address.getBytes());
        long ret = Math.abs(crc32.getValue() & 0xFFFFFFFF);
        return (int) ret;
    }
}
